#!/usr/bin/perl
#
# man2enko.pl
# convert manpage file to 'enko' file.
# 
#  'enko' file format is quick&dirty-ly designed by amorette,
# which stands for 'english-korean'. this will not completely
# works. but it will help you concentrating on what-you-do.
#
# bug report: amorettia@gmail.com
#
# ChangeLog:
#   2009-03-13  0.01     created by amorette
# 
use warnings;
use strict;


#
# PREPARE and CHECK.
#
our $VERSION = "0.01";

my $DIVLINE = "%%".('-'x75)."\n%%".('='x75)."\n\n\n\n";
my ( $file, $rev ) = @ARGV;

if (not defined($file) or not defined($rev)) {
    print "usage: man2enko.pl <manpage-file> <revision-number>\n";
    exit(1);
}


#
# OPEN FILE and DO THE PARSE !
#
open my $fh, '<', $file or die "file not found";

my @lines = <$fh>;
my %sect = ();

for my $i (0 .. $#lines) {
    my $l = $lines[$i];
    chomp($l);

    # ignore comment syntax
    if ($l =~ /^\.\\\"/) {
	$sect{$i} = 'white';
    }

    # only white spaces
    if ($l =~ /^ *$/) {
	$sect{$i} = 'white';
    }

    # end sentence
    if ($l =~ /\.$/) {
	$sect{$i+1} = 'start';
    }

    # start section
    if ($l =~ /^\.(TH|SH|SS|RS) /) {
	$sect{$i} = 'start';
    }

    # end section, treated as of white spaces.
    if ($l =~ /^\.(RE|LP) /) {
	$sect{$i} = 'white';
    }
}


#
# RE-ARRANGED PARSED HASH.
#
$sect{0} = 'start';
for my $i (sort {$a <=> $b} keys %sect) {
    if ($sect{$i} eq 'white' && $sect{$i+1}) {
	$sect{$i} = undef;
    }
}


#
# NICE! PRINT PRETTY with PARSED HASH.
#
my $n = 1;
print "%\%$rev\:$n".("="x(75-length("$rev\:$n")))."\n";
print $lines[0];

for my $i (1 .. $#lines) {
    my $l = $lines[$i];
    if (! $sect{$i}) {
	print $l;
    }
    elsif ($sect{$i} eq 'start') {
	$n++;
	print $DIVLINE;
	print "%\%$rev:$n".("="x(75-length("$rev\:$n")))."\n";
	print $l;
    }
    elsif ($sect{$i} eq 'white') {
	print $l;
	$n++;
	print $DIVLINE;
	print "%\%$rev:$n".("="x(75-length("$rev\:$n")))."\n";
    }
}

print $DIVLINE;


#
# BYE BYE :)
#
close $fh;
